package com.example.app2;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

//汇率计算，以及弹出新窗口以重新设置汇率标准！
public class Activity_rate extends AppCompatActivity implements Runnable {

    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";

    private static final String TAG = "汇率：";    //常量标签
    EditText rmb;
    TextView out;
    Float rate1 = 0.0f, rate2 = 0.0f, rate3 = 0.0f;      //初始化rate
    String update = "";
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
        rmb = findViewById(R.id.rmb);
        out = findViewById(R.id.output);
        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");
        Log.i("List", "lastRateDateStr=" + logDate);


        SharedPreferences spf = getSharedPreferences("rate_save", Activity.MODE_PRIVATE);
        rate1 = spf.getFloat("dollar_rate", 6.5203f);   //读取保存的修改的数据
        rate2 = spf.getFloat("eu_rate", 7.8133f);
        rate3 = spf.getFloat("jp_rate", 0.0601f);

        Thread thread = new Thread(this);        //创建线程
        thread.start();

        handler = new Handler(Looper.myLooper()) {                       //handler用来连接主线程和子线程
            public void handleMessage(Message msg) {
                if (msg.what == 2) {
                    SharedPreferences bd = (SharedPreferences) msg.obj;
                    rate1 = bd.getFloat("dollarRate", 0.0f);
                    rate2 = bd.getFloat("euRate", 0.0f);
                    rate3 = bd.getFloat("jpRate", 0.0f);

                    Log.i(TAG, "dollarRate:" + rate1);
                    Log.i(TAG, "euRate:" + rate2);
                    Log.i(TAG, "jpRate:" + rate3);

                }
                super.handleMessage(msg);
            }
        };

    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    protected void onDestroy() {
        super.onDestroy();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        String todayTime = String.valueOf(df.format(new Date(System.currentTimeMillis())));// 获取当前的日期
        saveExitTime(todayTime);
    }

    private void saveExitTime(String extiLoginTime) {
        SharedPreferences.Editor editor = getSharedPreferences("LastLoginTime", MODE_PRIVATE).edit();
        editor.putString("LoginTime", extiLoginTime);
        editor.apply();
    }


    public void cal(double rate, String mon) {                //核算函数
        String r = rmb.getText().toString();
        if (r != null && r.length() > 0) {
            double rm = Double.parseDouble(r);
            double dollar = rm / rate;
            out.setText(String.valueOf(dollar) + mon);
        } else {
            out.setText("未输入");
        }
    }

    public void dollar(View v) {
        cal(rate1, "美元");
    }       //三个按钮的事件处理方法

    public void eu(View v) {
        cal(rate2, "欧元");
    }

    public void jp(View v) {
        cal(rate3, "日元");
    }

    public void reset(View v) {
        Intent goNext = new Intent(this, Activity_rateSet.class);  //建立intent
        goNext.putExtra("dollar", rate1);      //往intent中放入数据
        goNext.putExtra("eu", rate2);
        goNext.putExtra("jp", rate3);
        startActivityForResult(goNext, 3);    //跳转到intent指定的界面，并且设置两个页面交互的requestCode
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {  //数据交互实现方法
        if (requestCode == 3 && resultCode == 1) {                         //通过requesCode和resulCode确定intent
            Bundle bundle = data.getExtras();
            rate1 = bundle.getFloat("new_dollar", 0.0f);    //获取返回的数据
            rate2 = bundle.getFloat("new_eu", 0.0f);
            rate3 = bundle.getFloat("new_jp", 0.0f);

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    //菜单的创建
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.item1) {
            Intent goNext = new Intent(this, Activity_rateSet.class);  //建立intent跳转到另一个activity
            goNext.putExtra("dollar", rate1);      //跳转时携带数据
            goNext.putExtra("eu", rate2);
            goNext.putExtra("jp", rate3);
            startActivityForResult(goNext, 3);    //跳转到intent指定的界面，并且设置两个页面交互的requestCode
        } else {
            Log.i(TAG, "没有点击item1");
        }
        return super.onOptionsItemSelected(item);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override     //实现Runnable接口中的run方法,用来实现子线程的操作
    public void run() {

        Log.i("List", "run...");
        List<String> retList = new ArrayList<String>();
        Message msg = handler.obtainMessage();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date(System.currentTimeMillis()));
        Log.i("run", "curDateStr:" + curDateStr + " logDate:" + logDate);
        if (curDateStr.equals(logDate)) {
            //如果相等，则不从网络中获取数据
            Log.i("run", "日期相等，从数据库中获取数据");
            DBManager dbManager = new DBManager(Activity_rate.this);
            for (RateItem rateItem : dbManager.listAll()) {
                retList.add(rateItem.getCurName() + "=>" + rateItem.getCurRate());
            }
        } else {
            Log.i("run", "日期不同，从网络中获取在线数据");
            //获取网络数据
            try {
                List<RateItem> rateList = new ArrayList<RateItem>();
                Document doc = Jsoup.connect("http://www.usd-cny.com/bankofchina.htm").get();

                Elements tables = doc.getElementsByTag("table");

                Element retTable = tables.get(5);
                Elements tds = retTable.getElementsByTag("td");
                int tdSize = tds.size();
                for (int i = 0; i < tdSize; i += 8) {
                    Element td1 = tds.get(i);
                    Element td2 = tds.get(i + 5);
                    //Log.i("www","td:" + td1.text() + "->" + td2.text());
                    float val = Float.parseFloat(td2.text());
                    val = 100 / val;
                    retList.add(td1.text() + "->" + val);

                    RateItem rateItem = new RateItem(td1.text(), td2.text());
                    rateList.add(rateItem);
                }
                DBManager dbManager = new DBManager(Activity_rate.this);
                dbManager.deleteAll();
                Log.i("db", "删除所有记录");
                dbManager.addAll(rateList);
                Log.i("db", "添加新记录集");

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //更新记录日期
            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(DATE_SP_KEY, curDateStr);
            edit.apply();
            Log.i("run", "更新日期结束：" + curDateStr);
        }

        msg.obj = retList;
        msg.what = 2;
        handler.sendMessage(msg);
    }
}